<?php
/*
 * @Author: 李明
 * @Date: 2021-09-04 18:02:18
 * @LastEditTime: 2022-01-17 17:19:12
 * @LastEditors: 李明
 * @Description: 
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/Message/MessageModelController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\Message;

use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Models\MessageModel;
use App\Models\SystemBase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 *	@appid							      	互亿无线apiid
 *	@appkey							      	互亿无线apikey
 *	@sms_send_time						  两次短信发送时间间隔 单位：秒
 *	@sms_send_num						    最大发送次数
 *	@sms_send_black_time				限制发送时间 单位：秒 (一小时为 60*60 = 3600 秒)  目前用作 有效时间
 *	@sms_valid_time				      有效时间 单位：秒 (一小时为 60*60 = 3600 秒)  
 *	@url								        接口地址
 *	@is_open_send_limit					是否开启发送限制（1开启 0关闭）
 */
$GLOBALS['ihuyi']['appid']          = 'C20083820';
$GLOBALS['ihuyi']['appkey']          = '18059b86854b9348c469ba6ff3821848';
$GLOBALS['ihuyi']['sms_send_time']      = 60;
$GLOBALS['ihuyi']['sms_send_num']      = 5;
$GLOBALS['ihuyi']['sms_send_black_time']  = 600;
$GLOBALS['ihuyi']['sms_valid_time']  = 600;
$GLOBALS['ihuyi']['url']          = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
$GLOBALS['ihuyi']['is_open_send_limit']    = 1;
class MessageModelController extends MessageController
{
    /**
     * @description: 添加模板
     * @param {Request} $request
     * @return {*}
     */
    public function messageModelAdd(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            // $worker_id = $tokenInfo['worker_id'];
            $all = $request->all();
            $content = $all['content'];
            $type = $all['type'];
            /*
            合同金额${orderMoney}
            还款金额${refund}
            合同编号${contractNum}
            出借人${username}
            借款人${borrower}
            垫资方${advance}
            客户经理${workername}
            生效时间${validtime}
            到期时间 ${endtime}
            签署时间${signtime}
            */
            $content = str_replace('${orderMoney}', '【变量】', $content);
            $content = str_replace('${refund}', '【变量】', $content);
            $content = str_replace('${contractNum}', '【变量】', $content);
            $content = str_replace('${username}', '【变量】', $content);
            $content = str_replace('${borrower}', '【变量】', $content);
            $content = str_replace('${advance}', '【变量】', $content);
            $content = str_replace('${workername}', '【变量】', $content);
            $content = str_replace('${validtime}', '【变量】', $content);
            $content = str_replace('${endtime}', '【变量】', $content);
            $content = str_replace('${signtime}', '【变量】', $content);
        } catch (\Throwable $th) {
            return LMReturn::Error('传参存在问题', 'MMCMMA2');
        }
        try { // 首先插入一条记录
            $company_id = env('COMPANY', 3);
            $message = MessageModel::create(
                [
                    'name' => $all['name'],
                    'content' => $all['content'],
                    'type' => $all['type'] ?? 1,
                    'company_id' => $company_id,
                    'status' => 1, //1待审核（可修改）| 2审核中 | 3审核通过 | 4审核失败
                    'count' => MessageController::messageCountMoney($content),
                ]
            );
        } catch (\Throwable $th) {
            return LMReturn::Error('模板提交失败，请重新尝试，失败多次，请联系管理员', 'MMCMMA1');
        }
        try { // 调用 ihuyi 接口
            return $this->changeWithMessageModel($message, $content, $type);
        } catch (\Throwable $th) {
            return LMReturn::Error('提交审核失败，可尝试重新提交', 'MMCMMA3');
        }
    }

    public function messageModelChange(Request $request)
    {
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
            }
            // $worker_id = $tokenInfo['worker_id'];
            $all = $request->all();
            $content = $all['content'];
            $id = $all['id'];
            $type = $all['type'];
            /*
            合同金额${orderMoney}
            还款金额${refund}
            合同编号${contractNum}
            出借人${username}
            借款人${borrower}
            垫资方${advance}
            客户经理${workername}
            生效时间${validtime}
            到期时间 ${endtime}
            签署时间${signtime}
            */
            $content = str_replace('${orderMoney}', '【变量】', $content);
            $content = str_replace('${refund}', '【变量】', $content);
            $content = str_replace('${contractNum}', '【变量】', $content);
            $content = str_replace('${username}', '【变量】', $content);
            $content = str_replace('${borrower}', '【变量】', $content);
            $content = str_replace('${advance}', '【变量】', $content);
            $content = str_replace('${workername}', '【变量】', $content);
            $content = str_replace('${validtime}', '【变量】', $content);
            $content = str_replace('${endtime}', '【变量】', $content);
            $content = str_replace('${signtime}', '【变量】', $content);
        } catch (\Throwable $th) {
            return LMReturn::Error('传参存在问题', 'MMCMMC2');
        }
        try {
            $msg_model = MessageModel::find($id);
            // 1待审核（可修改）| 2审核中 | 3审核通过 | 4审核失败 | 5删除
            $status = $msg_model->status;
            if ($status != 1) {
                return LMReturn::Error('该模板不允许进行修改', 'MMCMMC1');
            } else {
                return $this->changeWithMessageModel($msg_model, $content, $type);
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('查询修改存在问题', 'MMCMMC3');
        }
    }

    public function changeWithMessageModel(MessageModel $msg_model, $content, $type)
    {

        try { // 调用 ihuyi 接口
            $account = $GLOBALS['ihuyi']['appid'];
            $apikey =  $GLOBALS['ihuyi']['appkey'];
            $time = time();
            $password = $apikey;
            $url = 'http://106.ihuyi.com/webservice/sms.php?method=AddTemplate';
            $post_data = "account=" . $account
                . "&password=" . $password
                // . "&mobile=" . $mobile
                . "&content="  . rawurlencode($content);
            $gets = $this->xml_to_array($this->post($post_data, $url));
            // dd($gets);
            $code = $gets['AddTemplateResult']['code'];
            $why = $gets['AddTemplateResult']['msg'];
        } catch (\Throwable $th) {
            return LMReturn::Error('提交审核失败，可尝试重新提交', 'MMCMMA3');
        }

        if ($code == 2) { // 返回值为 2 时，表示添加成功
            try {
                $msg_model->status = 2;
                $msg_model->templateid = $gets['AddTemplateResult']['templateid'];
                $msg_model->why = $why;
                $msg_model->ihuyi_code = $code;
                $msg_model->type = $type;
                $msg_model->save();
                return LMReturn::Success($msg_model, $why);
            } catch (\Throwable $th) {
                return LMReturn::Error('模板提交失败，请重新尝试，失败多次，请联系管理员', 'MMC003');
            }
        } elseif ($code == 408) { // 这是因为重复提交
            try {
                $msg_model->status = 4;
                $msg_model->templateid = $gets['AddTemplateResult']['templateid'];
                $msg_model->why = $why;
                $msg_model->ihuyi_code = $code;
                $msg_model->save();
                return LMReturn::Error($why, 'MMCMMA4', $msg_model);
            } catch (\Throwable $th) {
                return LMReturn::Error('模板提交失败，请重新尝试，失败多次，请联系管理员', 'MMC003', $msg_model);
            }
            return LMReturn::Error($gets);
        } else {
            try {
                $msg_model->status = 1;
                $msg_model->templateid = $gets['AddTemplateResult']['templateid'];
                $msg_model->why = $why;
                $msg_model->ihuyi_code = $code;
                $msg_model->save();
                return LMReturn::Error('模板保存成功，提交审核失败，请重新尝试，' . $why . '错误代码' . $code, 'MMC004');
            } catch (\Throwable $th) {
                return LMReturn::Error('模板保存失败，请重新尝试，' . $why . '错误代码' . $code, 'MMC002');
            }
        }
    }

    /**
     * @description: 删除短信模板
     * @param {Request} $request
     * @return {*}
     */
    public function deleteMessageModel(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        try {
            $id = $all['id'];
        } catch (\Throwable $th) {
            return LMReturn::Error('非法传参');
        }
        try {
            $messageModel = MessageModel::find($id);
            $messageModel->status = 5; //1待审核（可修改）| 2审核中 | 3审核通过 | 4审核失败 | 5删除
            $messageModel->save();
            return  LMReturn::Success($messageModel, '删除成功');
        } catch (\Throwable $th) {
            return LMReturn::Error('发生错误', 'MMC005');
        }
    }
    /**
     * @description: 查询短信模板
     * @param {Request} $request
     * @return {*}
     */
    public function queryMessageModel(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }

        try {
            $all = $request->all();
            $where = [];
            if (isset($all['status'])) {
                $where[] = ['status', $all['status']];
            } else {
                $where[] = ['status', '!=', '5'];
            }
            if (isset($all['type'])) {
                $where[] = ['type', $all['type']];
            }
            $company_id = env('COMPANY', 3);
            $where[] = ['company_id', $company_id];
            $messageModelList = MessageModel::where($where)
                ->orderBy('update_time', 'desc')
                ->get();
            return  LMReturn::Success($messageModelList);
        } catch (\Throwable $th) {
            return LMReturn::Error('发生错误', 'MMC001');
        }
    }
    /**
     * @description: 注意下面是ihuyi的短信模板结果回调
     * @param {Request} $request
     * @return {*}
     */
    public function messageModelUpdateStatus(Request $request)
    {
        $all = $request->all();
        Log::debug('注意下面是ihuyi的短信模板结果回调');
        Log::debug($all);
        try {
            $code = $all['code'];
            $msg = $all['msg'];
            $templateid = $all['templateid'];
        } catch (\Throwable $th) {
            return LMReturn::Error('非法传参');
        }

        try {
            $messageModel = MessageModel::where('templateid', $templateid)->first();
            $messageModel->why = $msg;
            if ($code == '2') {
                $messageModel->status = '3'; //1待审核（可修改）| 2审核中 | 3审核通过 | 4审核失败 | 5删除
            } else {
                $messageModel->status = '4'; //1待审核（可修改）| 2审核中 | 3审核通过 | 4审核失败 | 5删除
            }
            $messageModel->save();
            return 'success';
        } catch (\Throwable $th) {
            return 'error';
        }
    }
}
